//
//  UserInfo.m
//  MYChatting
//
//  Created by mac on 16/7/30.
//  Copyright © 2016年 lhf. All rights reserved.
//

#import "UserInfo.h"

@implementation UserInfo

- (void)setExpires_in:(NSString *)expires_in{
    _expires_in = expires_in;
    
    _expires_date = [[NSDate date]initWithTimeIntervalSinceNow:[expires_in floatValue ]];
}



+ (NSArray *)properties{
    return @[@"access_token",@"expires_in",@"uid",@"expires_date",@"name",@"avatar_large",@"userLogin"];
}

+ (instancetype)userInfoWithDict:(NSDictionary *)dict{
    id obj = [[self alloc] init];
    for (NSString * property in [self properties]) {
        if (dict[property] != nil) {
            [obj setValue:dict[property] forKey:property];
        }
    }
    return obj;
}


//归档
//注意：基本数据类型的参数是不能直接转化为id类型的对象的
- (void)encodeWithCoder:(NSCoder *)coder
{
    
    [coder encodeObject:_access_token forKey:@"access_token"];
    [coder encodeObject:_expires_in forKey:@"expires_in"];
    [coder encodeObject:_expires_date forKey:@"expires_date"];
    [coder encodeObject:_uid forKey:@"uid"];
    [coder encodeObject:_name forKey:@"name"];
    [coder encodeObject:_avatar_large forKey:@"avatar_large"];
   
  
}




//解档
- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super init];
    if (self) {
       _access_token = [coder decodeObjectForKey:@"access_token"];
        _expires_in = [coder decodeObjectForKey:@"expires_in"];
        _expires_date = [coder decodeObjectForKey:@"expires_date"];
        _uid = [coder decodeObjectForKey:@"uid"];
        _name = [coder decodeObjectForKey:@"name"];
        _avatar_large = [coder decodeObjectForKey:@"avatar_large"];
        
    }
    return self;
}


//存储个人信息
- (void)saveUserInfo{
    //存储路径
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"userInfo.plist"];
    //保存自定义对象    self在类方法中代表类，在实例方法中代表实例对象
    [NSKeyedArchiver archiveRootObject:self toFile:path];
    NSLog(@"path=====%@",path);
}


//加载沙盒中的自定义对象
- (instancetype)loadUserInfo{
    //沙盒路径
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"userInfo.plist"];
    //解档对象
    UserInfo *userInfo = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    if ([userInfo.expires_date compare:[[NSDate alloc] init]] == NSOrderedDescending) {
        return userInfo;
    }else{
        return nil;
    }
   // return userInfo;
}

@end
